
const { signToken } = require("../../../middlear/token");
const ADMIN_USER = require("../../../model/admin_user-model");
const correlation_user_role = require("../../../model/role&user-model");
const userForRoleCollection = require("../../../model/role&user-model")
const { bcryptjs_Hash, bacypter_Compare } = require("../../../utils/bcrypt");
const { getFilter } = require("../../../utils/setFilter");
const { getDocumentDetail } = require("./r_role_user");
const deleteCorrelation = require("./r_role_user").deleteDocuments;


// 注册用户
const register = async ({ roleId, roleName, userId, passWord, userName, cost, imgUrl }) => {
    // 再查账号是否被注册了
    const queryUser = await ADMIN_USER.findOne({ userId });
    if (queryUser !== null) {
        return {
            status: "0001",
            message: "此用户名已经被注册",
        }
    }

    const password = await bcryptjs_Hash(passWord)// 进行加密
    // 可以注册
    const register = await ADMIN_USER.create({ roleId, roleName, userId, passWord: password, userName, cost, imgUrl })
    return {
        status: "0000",
        message: "注册成功",
    }




}
// 登录
const login = async ({ userId, passWord }) => {
    const res = await ADMIN_USER.findOne({ userId });
    if (res == null) {

        return {
            code: "0001",
            msg: "此用户名不存在",

        }
    }

    let bacypter_passWord = await bacypter_Compare(res.passWord, passWord)
    if (bacypter_passWord === false) {
        return {
            code: '0010',
            msg: "密码错误",

        }
    }
    console.log("登录成功：", res)
    return {
        code: 0,
        msg: "登录成功",
        data: {
            token: signToken({ userName: res.userName, userPwd: res.passWord }),
            userInfo: {
                _id: res._id,
                userName: res.userName || "用户名",
                userId: res.userId,
                userPhone: res.userPhone || "",
                imgUrl: res.imgUrl
            }
        }
    }
}

// 更新信息 如昵称 把需要修改的参数放到params对象中
const update = async ({ userId, _id, params = {} }) => {
    // findOneAndUpdate 可以返回修改后的数据
    const res = await ADMIN_USER.findOneAndUpdate({ _id }, {
        $set: {
            // userName
            ...params
        }
    }, { new: true })

    if (res._id) {
        return {
            code: 0,
            msg: "信息更新成功",
            data: {
                userInfo: {
                    _id: res._id,
                    userId: res.userId,
                    userName: res.userName,
                    userPhone: res.userPhone,
                    imgUrl: res.imgUrl
                }
            }
        }
    } else {
        return {
            code: "0010",
            msg: "信息更新失败，查不到此用户"
        }
    }



}

// 查询列表
const queryAdmin = async ({ current, pageSize, roleName, roleId, userId, userName, status }) => {
    try {
        let conditions = {
            userName: userName && { $regex: eval("/" + userName + "/i") },
            userId: userId && { $regex: eval("/" + userId + "/i") },
            roleName: roleName && { $regex: eval("/" + roleName + "/i") },
            roleId: roleId && { $regex: eval("/" + roleId + "/i") },
            status: roleId && { $regex: eval("/" + status + "/i") },
        }
        conditions = getFilter(conditions);
        console.log("current, pageSize,", current, pageSize,)
        const list = await ADMIN_USER.aggregate([
            {
                $match: conditions
            },
            { $sort: { createDate: 1 } },
            {
                $lookup: {
                    from: "correlation_user_roles",
                    localField: "userId",
                    foreignField: "userId",
                    as: "roleData"
                }
            },
            {
                $unwind: {
                    path: "$roleData",
                    preserveNullAndEmptyArrays: true
                }
            },
            {
                $addFields: {
                    roleId: { $ifNull: ["$roleData.roleId", null] },
                    roleName: { $ifNull: ["$roleData.roleName", null] }
                }
            },
            {
                $project: {
                    roleData: 0,
                    __v: 0,  // 显式排除 __v 字段
                    passWord: 0
                }
            },
            { $skip: (current - 1) * pageSize },
            { $limit: pageSize },
        ]);
        const totalCount = await ADMIN_USER.countDocuments(conditions);
        return {
            code: 0,
            msg: "查询成功",
            data: {
                list,
                totalCount
            }
        }
    } catch (error) {
        console.log("error", error)
        return {
            code: 12,
            msg: "查询出错，服务端故障"
        }
    }
}

// 删除
const deleteAdmin = async ({ ids = [] }) => {
    const deleteResult = await ADMIN_USER.deleteMany({
        _id: { $in: ids }
    });
    if (deleteResult.deletedCount) {
        //同时也删除（角色用户关系表）中的数据.
        await deleteCorrelation({ user_id: ids }).then((res) => {
            console.log("删除关联关系，", res)
        }).catch(err => {
            console.log("删除关联关系出错", err)
        })
        return {
            status: '0000',
            message: `删除了${deleteResult.deletedCount}条数据`
        }
    } else {
        return {
            status: '0010',
            message: `删除失败`
        }
    }
}

module.exports = {
    register, login, update, queryAdmin, deleteAdmin
}